package AccountWindow.SystemAdmin.NewRegisterWindow.Dao;

import AccountWindow.SystemAdmin.Account;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Vector;


public class NewRegisterDAO {
    //该类将与数据库的表相关的增、删、查、改操作抽离出来
    //同时也将account抽离
    String url = "jdbc:mysql://localhost:3306/hims";
    String user = "root";
    String password = "511300";
    public int add(Account account) throws Exception{
        Class.forName("com.mysql.cj.jdbc.Driver"); //注册驱动
        Connection con = DriverManager.getConnection(url, user, password);  //获取连接
        Statement stat = con.createStatement(); //获取执行者对象
        String sql = "INSERT INTO account VALUES ('"+account.accountID+"','"+account.accountCode+"','"+account.accountType+"')";
        int row = -1;
        row += stat.executeUpdate(sql);  //表示有x行受到影响，可以将add更为int型，若=1，表示插入成功，若不=1表示插入失败，并弹出相应的窗口提示用户

        if ("职工".equals(account.accountType)) {
            sql = "INSERT INTO employee (employeeID) VALUES ('"+account.accountID+"')";
        } else if ("酒店管理员".equals(account.accountType)) {
            sql = "INSERT INTO employee (hotelAdminID) VALUES ('"+account.accountID+"')";
        } else if ("系统管理员".equals(account.accountType)) {
            sql = "INSERT INTO employee (systemAdminID) VALUES ('"+account.accountID+"')";
        }

        row += stat.executeUpdate(sql);

        stat.close();
        con.close();
        return row;
    }

    public void remove(Account account) throws Exception{
        Class.forName("com.mysql.cj.jdbc.Driver"); //注册驱动
        Connection con = DriverManager.getConnection(url, user, password);  //获取连接
        Statement stat = con.createStatement(); //获取执行者对象
        String sql = "DELETE FROM accountTmp WHERE accountID = '"+account.accountID+"'";
        int row = stat.executeUpdate(sql);  //表示有x行受到影响，可以将add更为int型，若=1，表示删除成功，若不=1表示删除失败，并弹出相应的窗口提示用户
        System.out.println(row);
        stat.close();
        con.close();
    }

    public Vector<Vector> query() throws Exception{

        Vector<Vector> data = new Vector<>();

        Class.forName("com.mysql.cj.jdbc.Driver"); //注册驱动
        Connection con = DriverManager.getConnection(url, user, password);  //获取连接
        Statement stat = con.createStatement(); //获取执行者对象
        String sql = "SELECT * FROM accountTmp";
        ResultSet rs =stat.executeQuery(sql);

        while(rs.next()){

            String accountID = rs.getString("accountID");
            String accountCode = rs.getString("accountCode");
            String accountType = rs.getString("accountType");

            Vector line = new Vector();
            line.add(accountID);
            line.add(accountType);
            line.add(accountCode);

            data.add(line);

        }

        rs.close();
        stat.close();
        con.close();

        return data;
    }

}
